package com.health.mapp.impl;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.health.commons.PropertiesService;
import com.health.db.model.CourseShareLedger;
import com.health.db.model.CourseShareLedgerExample;
import com.health.db.model.EPayCashPayment;
import com.health.db.model.UserAccountVoucherBill;
import com.health.db.model.UserLIST;
import com.health.db.service.order.IEPayCashPaymentService;
import com.health.db.service.sm.IWXPayService;
import com.health.db.service.user.ICourseShareJournalService;
import com.health.db.service.user.ICourseShareLedgerService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.GetCourseShareCashApplyReq;
import com.health.mapp.bean.GetCourseShareCashApplyResp;
import com.health.mapp.bean.Header;
import com.health.mapp.service.SecureUtil;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.PropertiesUtil;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import com.health.pay.tencent.protocol.transfers.TransfersReq;
import com.health.pay.tencent.protocol.transfers.TransfersResp;

/**
 * 日志1:ePayCashPayment
 * 日志2:courseShareJournal
 * 日志3:course_share_voucher_bill
 * 
 * @author HiRoad
 *
 */
public class GetCourseShareCashApplyImpl implements ActionInterface {
	
	@Autowired
	private ICourseShareJournalService courseShareJournalService ;
	
	@Autowired
	private ICourseShareLedgerService courseShareLedgerService ; 
	
	@Autowired
	private IWXPayService wXPayService;
	
	@Autowired
	private IEPayCashPaymentService ePayCashPaymentService;
	
	@Autowired
	private IUserLISTService UserLISTService;
	
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		GetCourseShareCashApplyReq req=(GetCourseShareCashApplyReq) reqBean;
		GetCourseShareCashApplyResp _resp= new GetCourseShareCashApplyResp();
		
		String flag = req.getFlag();
			
		//flag=2为取消付款
		if (StringUtils.isNotEmpty(flag)&&("2").equals(flag)) {
		
		//flag=1为确认付款
		}else if (StringUtils.isNotEmpty(flag)&&("1").equals(flag)) {
		
			
		}else{
			
			Long userId = Long.valueOf(req.getUserId());
			String cashAmountStr = req.getGetCashAmount();
			
			
			if (userId==0) {
				_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
				_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
				return _resp;
			}else{
				
				CourseShareLedger  userAccountLedger = courseShareLedgerService.selectByUserId(userId);
				
				if (null== userAccountLedger) {
					_resp.setErrorCode(ResultCode.OPERATION_OTHER_ERROR);
					_resp.setErrorMsg("此用户无可提现的账户");
					return _resp;
				}
				BigDecimal temp ;
				
				if (StringUtils.isBlank(cashAmountStr)&&(userAccountLedger.getBalanceTotal().compareTo(BigDecimal.ZERO)>0)) {
					temp = userAccountLedger.getBalanceTotal();
				}else{
					
					try{
						BigDecimal amount=	new BigDecimal(cashAmountStr);
						
						if (userAccountLedger.getBalanceTotal().compareTo(amount)>0) {
							temp =amount;
						}else{
							temp = userAccountLedger.getBalanceTotal();
						}
					}catch (Exception e) {
						//传入不是数字型的报错
						_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
						_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
						return _resp;
					}
				}
				
				//最低取现金额为20元
				if (temp.compareTo(new BigDecimal(PropertiesService.getString("miniprogram.minicoursesharecashapply").trim()))>=0) {
					
					UserAccountVoucherBill userAccountVoucherBill = new UserAccountVoucherBill();
					userAccountVoucherBill.setRunFlag((short) 0);
					userAccountVoucherBill.setUserid(userAccountLedger.getAccountid());
					EPayCashPayment payment = this.packageInsertPayCashPaymentLog();
					payment.setPaycashTotal(temp);
					ePayCashPaymentService.insert(payment);
					//查询IP
					 String remoteIP=SecureUtil.getRemoteHost((HttpServletRequest) header.getHttpRequest());
					 
					 UserLIST user = UserLISTService.selectByUserId(userId);
					 
					 //账户未绑定
					 if (StringUtils.isEmpty(user.getWxopenid())) {
							_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_5005);
							_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_5005_NOTE);
							return _resp;
					}

					CourseShareLedger  userAccountLedgerUpdate = new CourseShareLedger();
					
					//账单表日志
					userAccountLedgerUpdate.setUpdateUserid(userId);
					userAccountLedgerUpdate.setAccountid(userId);
					userAccountLedgerUpdate.setBalanceTotal(new BigDecimal("0"));
					CourseShareLedgerExample courseShareLedgerExample= courseShareLedgerService.insertCourseShareCash(userAccountLedgerUpdate, String.valueOf(payment.getPaycashid()), temp);
					 
					//余额提现
					TransfersReq transfersReq = new TransfersReq
							( "首儿健康汇-余额提现", String.valueOf(payment.getPaycashid()), user.getWxopenid(), temp.multiply(new BigDecimal(100)).intValue(), "首儿健康汇-余额提现", remoteIP);
					TransfersResp refundResData =wXPayService.transfers(transfersReq);
					
					EPayCashPayment paymentUpdate = new EPayCashPayment(); 
					paymentUpdate.setPaycashid(payment.getPaycashid());
					if (!refundResData.getResult_code().equals("SUCCESS")) {
						paymentUpdate.setRunStatus(String.valueOf(Constant.CONSTANTS_PAY_STATUS_CLOSE));
						ePayCashPaymentService.updateByPayCashIDSelective(paymentUpdate);
						
						CourseShareLedger  userAccountLedgerReset = new CourseShareLedger();
						
						//账单表日志
						userAccountLedgerReset.setUpdateUserid(userId);
						userAccountLedgerReset.setAccountid(userId);
						userAccountLedgerReset.setBalanceTotal(temp);
						courseShareLedgerService.reset(userAccountLedgerReset, courseShareLedgerExample);
						_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_4005);
						_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_4005_NOTE);
						return _resp;
					}
				}else{
					_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_4004);
					_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_4004_NOTE);
					return _resp;
				}
			}
		}
		return _resp;
	}
	
	
	
	/**
	 * 	 支付日志塞入
	 * @param ePayCashPayment
	 * @return payCashId
	 */
	public EPayCashPayment packageInsertPayCashPaymentLog( ) {
		
		EPayCashPayment payment = new EPayCashPayment();
		
		payment.setCreateDate(new Date());
		payment.setPaycashIdno("");
		payment.setPaystepid(Constant.CONSTANTS_PAY_STEP_4);
		payment.setPaycashSign(Constant.CONSTANTS_ORDER_DIRECT_OP);
		payment.setPaycashTypeid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_WEIXIN));
		
		payment.setCreateUserid(PropertiesUtil.getLong("defalutUser",2));
		payment.setUpdateUserid(PropertiesUtil.getLong("defalutUser",2));
		payment.setRunStatus(String.valueOf(Constant.CONSTANTS_PAY_STATUS_NORMAL));
		
		payment.setPaycashTypeid(Integer.valueOf(Constant.CONSTANTS_PAYMENT_WEIXIN));
		payment.setPaycashTypeName(Constant.CONSTANTS_VOUCHERNAME_2);
		
		payment.setSourceid(Constant.CONSTANTS_PAY_ACTION_ID_71);

		return payment;
	}
	

	public ICourseShareJournalService getCourseShareJournalService() {
		return courseShareJournalService;
	}


	public void setCourseShareJournalService(
			ICourseShareJournalService courseShareJournalService) {
		this.courseShareJournalService = courseShareJournalService;
	}


	public ICourseShareLedgerService getCourseShareLedgerService() {
		return courseShareLedgerService;
	}


	public void setCourseShareLedgerService(
			ICourseShareLedgerService courseShareLedgerService) {
		this.courseShareLedgerService = courseShareLedgerService;
	}


	public IWXPayService getwXPayService() {
		return wXPayService;
	}


	public void setwXPayService(IWXPayService wXPayService) {
		this.wXPayService = wXPayService;
	}


	public IEPayCashPaymentService getePayCashPaymentService() {
		return ePayCashPaymentService;
	}


	public void setePayCashPaymentService(
			IEPayCashPaymentService ePayCashPaymentService) {
		this.ePayCashPaymentService = ePayCashPaymentService;
	}


	public IUserLISTService getUserLISTService() {
		return UserLISTService;
	}


	public void setUserLISTService(IUserLISTService userLISTService) {
		UserLISTService = userLISTService;
	}
	
}
